#include "ffopthandle.h"

#include <QDir>
#include <QFile>

#include "log/loghandle.h"

FFOptHandle::FFOptHandle(QPlainTextEdit *parent):
    w(parent) {}

FFOptHandle::~FFOptHandle() {}

void FFOptHandle::generateFile(QStringList file_tree) {
    for(int i = 0; i < file_tree.size(); i ++) {
        QFile file(file_tree.at(i));
        if (!file.open(QIODevice::WriteOnly)) {
            LogHandle(w) << "File" << file_tree.at(i) << "create failed!";
            continue;
        }
        file.close();
    }
}

void FFOptHandle::generateFolder(QStringList folder_tree) {
    for(int i = 0; i < folder_tree.size(); i ++) {
        QDir().mkdir(folder_tree.at(i));
    }
}

void FFOptHandle::copyFile(QList<CopyTree> file_ctree) {
    for(int i = 0; i < file_ctree.size(); i ++) {
        QFile file_r(file_ctree.at(i).from),
              file_w(file_ctree.at(i).to);
        QByteArray tmp_data;

        if(!file_r.exists()) {
            LogHandle(w) << "File" << file_ctree.at(i).from << "isn't existed!";
            continue;
        }

        if (!file_r.open(QIODevice::ReadOnly)) {
            LogHandle(w) << "File" << file_ctree.at(i).from << "open failed!";
            continue;
        }
        tmp_data = file_r.readAll();
        file_r.close();

        if (!file_w.open(QIODevice::WriteOnly)) {
            LogHandle(w) << "File" << file_ctree.at(i).to << "create failed!";
            continue;
        }
        file_w.write(tmp_data);
        file_w.close();
    }
}

void FFOptHandle::copyFolder(QList<CopyTree> folder_ctree) {
    for(int i = 0; i < folder_ctree.size(); i ++) {
        QDir folder_r(folder_ctree.at(i).from);
        QDir folder_w(folder_ctree.at(i).to);

        if (!folder_w.exists()) {
            QDir().mkdir(folder_ctree.at(i).to);
        }

        foreach (const QFileInfo &fileInfo, folder_r.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot)) {
            QString fileName = fileInfo.fileName();
            CopyTree folder_cpy;
            folder_cpy.from = QString("%1/%2").arg(folder_ctree.at(i).from, fileName);
            folder_cpy.to = QString("%1/%2").arg(folder_ctree.at(i).to, fileName);

            if (fileInfo.isDir()) {
                generateFolder({folder_cpy.to});
            } else {
                copyFile({folder_cpy});
            }
        }
    }
}
